package com.nuaa.ojjudgecodesandbox.utils;

import cn.hutool.core.date.StopWatch;
import com.nuaa.ojjudgecodesandbox.model.ExecuteMessage;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @Author ortonzhu
 * @Date 2024/10/20 14:08
 */
public class ProcessUtils {
    /**
     * @param runProcess 进程
     * @param opName     操作名称
     * @return
     */
    public static ExecuteMessage runProcessAndGetMessage(Process runProcess, String opName) {
        ExecuteMessage executeMessage = new ExecuteMessage();
        try {
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            int exitValue = runProcess.waitFor();
            executeMessage.setExitValue(exitValue);
            if (exitValue == 0) {
                System.out.println(opName + "成功");
                //分批获取输出
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
                // 分行读取
                StringBuilder compileOutput = new StringBuilder();
                String compileOutputLine;
                while ((compileOutputLine = bufferedReader.readLine()) != null) {
                    compileOutput.append(compileOutputLine);
                }
                executeMessage.setMessage(compileOutput.toString());
            } else {
                // 异常退出
                System.out.println(opName + "失败，错误码：" + exitValue);
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
                // 分行读取
                StringBuilder compileOutput = new StringBuilder();
                String compileOutputLine;
                while ((compileOutputLine = bufferedReader.readLine()) != null) {
                    compileOutput.append(compileOutputLine);
                }
                //错误输出
                BufferedReader errorBufferedReader = new BufferedReader(new InputStreamReader(runProcess.getErrorStream()));
                StringBuilder errorCompileOutput = new StringBuilder();
                String errorBufferedLine;
                while ((errorBufferedLine = errorBufferedReader.readLine()) != null) {
                    errorCompileOutput.append(errorBufferedLine);
                }
                executeMessage.setErrorMessage(errorCompileOutput.toString());
            }
            stopWatch.stop();
            executeMessage.setTime(stopWatch.getLastTaskTimeMillis());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return executeMessage;

    }

}
